package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j

public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")

    public R page(int page, int pageSize, String name) {
        //构建分页
        IPage<Setmeal> pageInfo = new Page<>(page, pageSize);
        //构建条件
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //根据名称模糊查询
        lqw.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        //根据修改时间倒叙排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //执行查询
        setmealService.page(pageInfo, lqw);

        IPage<SetmealDto> resultPage = new Page<>(); //返回的结果Page
        //把原始的pageInfo的数据拷贝至resultPage，排除records。拷贝上：总数据量，当前页，每页显示数量，总页数
        BeanUtils.copyProperties(pageInfo, resultPage, "records");

        List<Setmeal> records = pageInfo.getRecords();//原始查询的数据集
        //新的数据集：包含分类名称
        List<SetmealDto> resultList = records.stream().map(setmeal -> {
            //循环一遍构建一个dto
            SetmealDto setmealDto = new SetmealDto();
            //把套餐的数据拷贝到dto
            BeanUtils.copyProperties(setmeal, setmealDto);
            //根据分类的id查询分类对象
            Category category = categoryService.getById(setmealDto.getCategoryId());
            if (category != null) {
                //给dto设置分类名称
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;
            //转换为dto的集合
        }).collect(Collectors.toList());

        //把新的数据集设置到resultPage
        resultPage.setRecords(resultList);

        return R.success(resultPage);
    }

    /**
     * 根据条件查套餐数据
     */
    @GetMapping("/list")
    @Cacheable(value = "setmeal",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R list(Setmeal setmeal) {
        Long categoryId = setmeal.getCategoryId();//前端传递过来的分类id
        Integer status = setmeal.getStatus();//前端传递过来的状态
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(null != categoryId, Setmeal::getCategoryId, categoryId);
        lqw.eq(null != status, Setmeal::getStatus, status);
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmealList = setmealService.list(lqw);
        return R.success(setmealList);
    }

    /**
     * 新增套餐
     *
     * @param dto
     * @return
     */
    @PostMapping
    @CacheEvict(cacheNames = "setmeal", key = "#dto.categoryId+'_1'")
    public R saveWithDish(@RequestBody SetmealDto dto) {
        log.info("新增套餐：" + dto);
        setmealService.saveWithDish(dto);
        return R.success("新增套餐成功");
    }

    /**
     * 修改售卖状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(cacheNames = "setmeal", allEntries = true)//清空以setmeal开头的所有缓存
    public R status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        setmealService.updateByStatus(status, ids);
        return R.success("菜品状态已经更改成功");
    }

    /**
     * 根据id集合删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmeal",allEntries = true) //清除setmeal名称下,所有的缓存数据
    public R deleteByIds(@RequestParam List<Long> ids) {
        log.info("删除套餐ids:{}", ids);
        setmealService.deleteByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 根据id查套餐信息
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getByIdWithFlavor(id);
        return R.success(setmealDto);
    }


    @PutMapping
    @Transactional  //开启事务注解
    @CacheEvict(value = "setmeal",key = "#dto.categoryId +'_'+#dto.status")
    public R updateById(@RequestBody SetmealDto dto) {
        setmealService.updateWithFlavor(dto);
        return R.success("修改成功");
    }
}